/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.taokeorder.web;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.common.utils.time.DateFormatUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.taokeorder.entity.TTaokeOrder;
import com.jeeplus.modules.taokeorder.service.TTaokeOrderService;

/**
 * 淘客订单管理Controller
 * @author ws
 * @version 2019-11-09
 */
@Controller
@RequestMapping(value = "${adminPath}/taokeorder/tTaokeOrder")
public class TTaokeOrderController extends BaseController {

	@Autowired
	private TTaokeOrderService tTaokeOrderService;
	
	@ModelAttribute
	public TTaokeOrder get(@RequestParam(required=false) String id) {
		TTaokeOrder entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tTaokeOrderService.get(id);
		}
		if (entity == null){
			entity = new TTaokeOrder();
		}
		return entity;
	}
	
	/**
	 * 淘客订单管理列表页面
	 */
	@RequiresPermissions("taokeorder:tTaokeOrder:list")
	@RequestMapping(value = {"list", ""})
	public String list(TTaokeOrder tTaokeOrder, Model model) {
		model.addAttribute("tTaokeOrder", tTaokeOrder);
		return "modules/taokeorder/tTaokeOrderList";
	}
	
		/**
	 * 淘客订单管理列表数据
	 */
	@ResponseBody
	@RequiresPermissions("taokeorder:tTaokeOrder:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(TTaokeOrder tTaokeOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<TTaokeOrder> page = tTaokeOrderService.findPage(new Page<TTaokeOrder>(request, response), tTaokeOrder); 
		if(page.getList()!=null && page.getList().size()>0){
			for(TTaokeOrder o:page.getList()){
				//时间转换开始
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = null;
				try {
					date = simpleDateFormat.parse(DateFormatUtil.DEFAULT_ON_SECOND_FORMAT.format(o.getTkCreateTime()));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				long ts = date.getTime();
				Date current= null;
				try {
					current = simpleDateFormat.parse("2020-06-01 00:00:00");
				} catch (ParseException e) {
					e.printStackTrace();
				}
				long currents = current.getTime();
				//时间转换结束
				String fl;
				if(ts>=currents){
					fl="0.3";
				}else{
					fl="0.35";
				}
				//费率
				if(o.getType().equals("0")){
					if(StringUtils.isNotBlank(o.getPubSharePreFee())){
						o.setYgtb((new BigDecimal(o.getPubSharePreFee()).multiply(new BigDecimal(fl)).setScale(2, BigDecimal.ROUND_DOWN)).toString());
					}
					if(StringUtils.isNotBlank(o.getTotalCommissionFee())){
						o.setJstb((new BigDecimal(o.getTotalCommissionFee()).multiply(new BigDecimal(fl)).setScale(2, BigDecimal.ROUND_DOWN)).toString());
					}
				}else{
					if(StringUtils.isNotBlank(o.getPubSharePreFee())){
						o.setYgtb((new BigDecimal(o.getPubSharePreFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString());
					}
					if(StringUtils.isNotBlank(o.getTotalCommissionFee())){
						o.setJstb((new BigDecimal(o.getTotalCommissionFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString());
					}
				}
			}
		}
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑淘客订单管理表单页面
	 */
	@RequiresPermissions(value={"taokeorder:tTaokeOrder:view","taokeorder:tTaokeOrder:add","taokeorder:tTaokeOrder:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(TTaokeOrder tTaokeOrder, Model model) {
		model.addAttribute("tTaokeOrder", tTaokeOrder);
		return "modules/taokeorder/tTaokeOrderForm";
	}

	/**
	 * 保存淘客订单管理
	 */
	@ResponseBody
	@RequiresPermissions(value={"taokeorder:tTaokeOrder:add","taokeorder:tTaokeOrder:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(TTaokeOrder tTaokeOrder, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(tTaokeOrder);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		tTaokeOrderService.save(tTaokeOrder);//保存
		j.setSuccess(true);
		j.setMsg("保存淘客订单管理成功");
		return j;
	}
	
	/**
	 * 删除淘客订单管理
	 */
	@ResponseBody
	@RequiresPermissions("taokeorder:tTaokeOrder:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(TTaokeOrder tTaokeOrder) {
		AjaxJson j = new AjaxJson();
		tTaokeOrderService.delete(tTaokeOrder);
		j.setMsg("删除淘客订单管理成功");
		return j;
	}
	
	/**
	 * 批量删除淘客订单管理
	 */
	@ResponseBody
	@RequiresPermissions("taokeorder:tTaokeOrder:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			tTaokeOrderService.delete(tTaokeOrderService.get(id));
		}
		j.setMsg("删除淘客订单管理成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("taokeorder:tTaokeOrder:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(TTaokeOrder tTaokeOrder, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "淘客订单管理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<TTaokeOrder> page = tTaokeOrderService.findPage(new Page<TTaokeOrder>(request, response, -1), tTaokeOrder);
    		new ExportExcel("淘客订单管理", TTaokeOrder.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出淘客订单管理记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("taokeorder:tTaokeOrder:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<TTaokeOrder> list = ei.getDataList(TTaokeOrder.class);
			for (TTaokeOrder tTaokeOrder : list){
				try{
					tTaokeOrderService.save(tTaokeOrder);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条淘客订单管理记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条淘客订单管理记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入淘客订单管理失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入淘客订单管理数据模板
	 */
	@ResponseBody
	@RequiresPermissions("taokeorder:tTaokeOrder:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "淘客订单管理数据导入模板.xlsx";
    		List<TTaokeOrder> list = Lists.newArrayList(); 
    		new ExportExcel("淘客订单管理数据", TTaokeOrder.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }

}